#ifndef IR_H
#define IR_H

#include <Arduino.h>
#include <TM1637Display.h>

// setting the sensor in the pin A0
// Command - LM35 name_of_variable(analog_pin);
#define LM35_PIN A0
#define FRONT_LEFT_IR_AVOIDANCE_PIN 10

long previousMillis_LM35; // for LM35
const int interval_LM35 = 10000;
float PreviousValue = 0;
float tempC;

// Empty. Things are done in Tasks.
int CLK = 2;
int DIO = 3;
TM1637Display display(CLK, DIO);
// degree celsius symbol
const uint8_t celsius[] = {
    SEG_A | SEG_B | SEG_F | SEG_G, // Degree symbol
    SEG_A | SEG_D | SEG_E | SEG_F  // C
};



long readVcc()
{
  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
  ADMUX = _BV(MUX5) | _BV(MUX0);
#elif defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
  ADMUX = _BV(MUX3) | _BV(MUX2);
#else
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#endif

  delay(2);            // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA, ADSC))
    ; // measuring

  uint8_t low = ADCL;  // must read ADCL first - it then locks ADCH
  uint8_t high = ADCH; // unlocks both

  long result = (high << 8) | low;

  result = 1108848L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
  return result;              // Vcc in millivolts
}

void read_LM35()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis_LM35 >= interval_LM35)
  {
    previousMillis_LM35= currentMillis; // Remember the time
    long vcc = readVcc();                 // mV
    Serial.println(vcc);
    tempC = analogRead(LM35_PIN);
    tempC *= vcc;
    tempC /= 10230;
    Serial.println(tempC);
    if (tempC != PreviousValue)
    {
      PreviousValue = tempC;
      display.showNumberDec(tempC, false, 2, 0);
      display.setSegments(celsius, 2, 2);
    };
  };
};

void setup_ir_lm35_tm1637()
{
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
  display.clear();
  display.setBrightness(2); // set the brightness to 7 (0:dimmest, 7:brightest)

  long vcc = readVcc();                 // mV
  Serial.println(vcc);
  tempC = analogRead(LM35_PIN);
  tempC *= vcc;
  tempC /= 10230;
  display.showNumberDec(tempC, false, 2, 0);
  display.setSegments(celsius, 2, 2);
  PreviousValue = tempC;
};

void loop_ir_lm35_tm1637()
{
  read_LM35();
  Serial.println(digitalRead(FRONT_LEFT_IR_AVOIDANCE_PIN));
}


#endif /* IR_H */